package httpproxy.utils;

import java.io.BufferedInputStream;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;

public class RequestConverter {

	public static HttpGet convertGetRequest(HttpServletRequest request) throws Exception {
		HttpGet httpget = new HttpGet(request.getRequestURL().toString());
		httpget.setConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build());
		Enumeration<String> enums = request.getHeaderNames();
		while (enums.hasMoreElements()) {
			String headerName = enums.nextElement();
			String headerValue = request.getHeader(headerName);
			httpget.setHeader(headerName, headerValue);
		}
		return httpget;
	}

	public static HttpPost convertPostRequest(HttpServletRequest request) throws Exception {
		HttpPost httppost = new HttpPost(request.getRequestURL().toString());
		httppost.setConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build());
		Enumeration<String> enums = request.getHeaderNames();
		while (enums.hasMoreElements()) {
			String headerName = enums.nextElement();
			String headerValue = request.getHeader(headerName);
			httppost.setHeader(headerName, headerValue);
		}
		return httppost;
	}

	public static void convertResponse(CloseableHttpResponse httpResponse, HttpServletResponse servletResponse)
			throws Exception {
		boolean isText = false;
		for (Header header : httpResponse.getAllHeaders()) {
			if(header.getName().equals("Content-Type") && header.getValue().contains("text")){
				isText = true;
			}
			servletResponse.setHeader(header.getName(), header.getValue());
			//System.out.println(header.getName() + "-----------" + header.getValue());
		}
		HttpEntity entity = httpResponse.getEntity();
		if (!isText && entity != null && entity.getContent() != null) {
			BufferedInputStream instream = new BufferedInputStream(entity.getContent());
			int j = 0;
			while ((j = instream.read()) != -1) {
				servletResponse.getWriter().write(j);
			}
		} else {
			servletResponse.getWriter().write(EntityUtils.toString(entity));
		}
		//httpResponse.close();
	}
}
